package com.hellogood.yaohuo.client.basic;

import java.util.List;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.hellogood.yaohuo.shared.entity.Size;
import com.hellogood.yaohuo.shared.services.SizeService;
import com.smartgwt.client.types.TreeModelType;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.tree.Tree;
import com.smartgwt.client.widgets.tree.TreeGrid;
import com.smartgwt.client.widgets.tree.TreeGridField;
import com.smartgwt.client.widgets.tree.TreeNode;

public class SizeController {

	private TreeNode[] treeNodes = null;	
	private TreeGrid treeGrid = null;
	
	public SizeController() {
		initData();
		initView();
	}

	public void initData() {
		SizeService.Util.getInstance().getAllSizeList(new GetAllAsyncCallback());
	}

	private void initView() {
		treeGrid = new TreeGrid();
		treeGrid.setFields(new TreeGridField("name", "尺寸"));
		treeGrid.setWidth("100%");
		treeGrid.setHeight("100%");
	}

	public Canvas getCanvas() {
		return treeGrid;
	}

	private class GetAllAsyncCallback implements AsyncCallback<List<Size>> {

		@Override
		public void onFailure(Throwable caught) {
			SC.say(caught.getMessage());
		}

		@Override
		public void onSuccess(List<Size> result) {
			if (result != null) {
				treeNodes = new TreeNode[result.size()];
				for (int i = 0; i < result.size(); i++) {
					Size s = result.get(i);
					TreeNode r = new TreeNode();
					r.setAttribute("code", s.getSizeCode());
					r.setAttribute("name", s.getSize1()+"/"+s.getSize2());
					r.setAttribute("isOpen", true);
					r.setAttribute("parentId", "-1");
					treeNodes[i] = r;
				}

				Tree tree = new Tree();
				tree.setModelType(TreeModelType.PARENT);
				tree.setNameProperty("name");
				tree.setRootValue("-1");
				tree.setIdField("nodeId");
				tree.setParentIdField("parentId");
				tree.setOpenProperty("isOpen");
				tree.setData(treeNodes);

				treeGrid.setData(tree);
			}
		}
	}

}
